package com.manager.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.manager.pojo.TbCommodity;
import com.manager.pojo.TbInlibrary;
import com.manager.service.InLibraryService;
import com.manager.service.StorageService;
import com.manager.vo.IDUtils;
import com.manager.vo.TbUserEx;

/**
 * 
 * @Title:  InLibraryControl.java     
 * @Description:    入库Controller
 * @author:      
 * @date:   2019年2月17日 下午1:26:07   
 * @version V1.0
 */
@Controller
public class InLibraryControl {

	@Autowired
	private InLibraryService inLibraryService;
	
	@Autowired
	private StorageService storageService; 
	
	//获取库存分页list
	@RequestMapping("/inlibrary-list")	
	public String getStorageList(Integer page,Integer rows,String s_type,String like,Integer flag,String start,String end,Model model) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		if(flag!=null && flag == 1 && !start.isEmpty() && !end.isEmpty()) {
			
			Date dstart = null;
			Date dend = null;
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			
			try {
				dstart = sdf.parse(start);
				dend = sdf.parse(end);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			tbUserEx = inLibraryService.getInLibraryListByDateTime(page, rows, dstart, dend);
			
			tbUserEx.setFlag(flag);
			tbUserEx.setStart(start);
			tbUserEx.setEnd(end);
			model.addAttribute("tbUserEx", tbUserEx);
			
			return "inlibrary-list";
		}
		
		
		//判断查询模式
		if(s_type == null || like==null || s_type.isEmpty() || like.isEmpty()) {
			
			s_type = null;
			like=null;
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		
		//商品名称查询
		if( s_type!=null && s_type.equals("name")) {
			
			like = like.trim();
			
			try {		//like参数存在中文 进行转码
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}  
			
			//获取 商品名称分页
			tbUserEx = inLibraryService.getInLibraryListByName(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("type")) {	//商品类型查询
			
			like = like.trim();
			
			try {	//like参数存在中文 进行转码
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}  

			//获取分页查询
			tbUserEx = inLibraryService.getInLibraryListByType(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("SKU")) {		//根据SKU查询

			//获取分页查询
			like = like.trim();
			tbUserEx = inLibraryService.getInLibraryListBySKU(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
		}else {
			
			//查询全部
			tbUserEx = inLibraryService.getInLibraryList(page, rows);
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		//判断成功失败码
		if(tbUserEx.getCode()!=200) {
			return "inlibrary-list";
		}
		
		//添加到model容器 方便前端访问查看
		model.addAttribute("tbUserEx", tbUserEx);
		
		return "inlibrary-list";
	}
	
	
	
	//添加页面的列表获取
	@RequestMapping("/inlibrary-add")
	public String inlibraryAdd(Model model) {
		
		TbUserEx tbUserEx = null;
		
		tbUserEx = storageService.getStorageList();
		
		model.addAttribute("tbUserEx", tbUserEx);
		
		return "inlibrary-add";
	}
	
	@RequestMapping("/inlibraryadd")
	@ResponseBody		//将上传的文件 路径 和信息  添加到数据库
	public TbUserEx inlibraryAdds(TbInlibrary tbInlibrary,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		//路径拼接
		String webinf_root = request.getRealPath("/WEB-INF");
		String web_img_path = tbInlibrary.getImg();
		web_img_path = web_img_path.substring(1, web_img_path.length());
		String old_img = webinf_root.concat(web_img_path);
		String new_img  = old_img.replaceAll("temp", "upload");
		
		File oldFile=new File(old_img);
		File newFile = new File(new_img);
		
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
        	//文件拷贝临时文件复制到 upload目录
        	FileUtils.copyFile(oldFile, newFile);
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
			tbUserEx.setCode(500);
	        tbUserEx.setError("入库添加异常");
	        return tbUserEx;
		} catch (IOException e) {

			e.printStackTrace();
			tbUserEx.setCode(500);
	        tbUserEx.setError("入库添加异常");
	        return tbUserEx;
		}
        
        //字符串分割 WEB-INF 取后面的路径存储到数据
       String arr[] = new_img.split("WEB-INF");
       System.out.println("."+arr[1]);
       //临时文件删除
       oldFile.delete();
        //添加到数据库
       tbInlibrary.setImg("."+arr[1]);
       tbInlibrary.setDtime(new Date());
       tbInlibrary.setLess(0);
       tbInlibrary.setMany(0);
       tbInlibrary.setLesswarning(0);
       tbInlibrary.setManywarning(0);
       tbInlibrary.setSku(String.valueOf(IDUtils.genItemId()));
      
       TbCommodity tbCommodity = null;
       try {
    	   tbCommodity = storageService.getTbCommodityById(tbInlibrary.getSid());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("添加入库记录异常");
			return tbUserEx;
		}
       if(tbCommodity==null) {
    	   tbUserEx.setCode(400);
			tbUserEx.setError("添加入库记录失败");
			return tbUserEx;
       }
       
       tbInlibrary.setName(tbCommodity.getName());
       
       tbUserEx = inLibraryService.addInLibrary(tbInlibrary);
       
       tbUserEx.setCode(200);
       tbUserEx.setMsg("添加入库记录异常");
       
       return tbUserEx;
	}
	
	//入库的编辑
	@RequestMapping("/inlibraryedit")
	@ResponseBody
	public TbUserEx inlibraryEdits(TbInlibrary tbInlibrary,String dtimes,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		TbInlibrary old_tbInlibrary = null;
		
		try {
			
			TbCommodity tbCommodity = storageService.getTbCommodityById(tbInlibrary.getSid());
			tbInlibrary.setName(tbCommodity.getName());
			
			DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
			tbInlibrary.setDtime(dateformat.parse(dtimes));
			
			old_tbInlibrary = inLibraryService.getTbInlibraryById(tbInlibrary.getId());
		} catch (Exception e1) {

			e1.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("入库记录编辑获取异常");
			return tbUserEx;
		}
		
		if(!old_tbInlibrary.getImg().equals(tbInlibrary.getImg())) {
			
			//路径拼接
			String webinf_root = request.getRealPath("/WEB-INF");
			String web_img_path = tbInlibrary.getImg();
			web_img_path = web_img_path.substring(1, web_img_path.length());
			String old_img = webinf_root.concat(web_img_path);
			String new_img  = old_img.replaceAll("temp", "upload");
			
			File oldFile=new File(old_img);
			File newFile = new File(new_img);
			
	        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	        try {
	        	//文件拷贝临时文件复制到 upload目录
	        	FileUtils.copyFile(oldFile, newFile);
			} catch (IllegalStateException e) {

				e.printStackTrace();
				tbUserEx.setCode(500);
		        tbUserEx.setError("入库编辑异常");
		        return tbUserEx;
			} catch (IOException e) {

				e.printStackTrace();
				tbUserEx.setCode(500);
		        tbUserEx.setError("入库编辑异常");
		        return tbUserEx;
			}
	        
	        //字符串分割 WEB-INF 取后面的路径存储到数据
	        String arr[] = new_img.split("WEB-INF");
			System.out.println("."+arr[1]);
			  
			//临时文件删除
			oldFile.delete();
	      
			String data_old_img = old_tbInlibrary.getImg();
			String old_web_img_path = data_old_img.substring(1, data_old_img.length());
			String data_old_img_path = webinf_root.concat(old_web_img_path);
			
			File old = new File(data_old_img_path);
			old.delete();
			tbInlibrary.setImg("."+arr[1]);
			System.out.println("与数据库图片不一样");
			
		}else {
			System.out.println("与数据库图片一样");
		}
		
		tbUserEx = inLibraryService.editInLibrary(tbInlibrary);
		
		return tbUserEx;
	}
	
	
	//入库的编辑页面访问
	@RequestMapping("/inlibrary-edit")
	public String inlibraryEdit(Integer id,Model model) {
		
		TbInlibrary tbInlibrary = null;
		TbUserEx tbUserEx = null;
		
		try{
			tbInlibrary = inLibraryService.getTbInlibraryById(id);
			tbUserEx = storageService.getStorageList();
		}catch(Exception e) {
			e.printStackTrace();
			
		}
		
		model.addAttribute("tbInlibrary", tbInlibrary);
		model.addAttribute("tbUserEx", tbUserEx);
		
		return "inlibrary-edit";
	}
	
	//入库的删除
	@RequestMapping("/inlibrary-del")
	@ResponseBody
	public TbUserEx inlibraryDel(Integer id,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		Boolean result = false;
		
		try{
			TbInlibrary tbInlibrary = inLibraryService.getTbInlibraryById(id);
			String webinf_root = request.getRealPath("/WEB-INF");
			String web_img_path = tbInlibrary.getImg();
			web_img_path = web_img_path.substring(1, web_img_path.length());
			String old_img = webinf_root.concat(web_img_path);
			File file = new File(old_img);
			file.delete();
			
			tbUserEx = inLibraryService.delnLibrary(id);

		}catch(Exception e) {
			
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("入库删除异常");
			return tbUserEx;
		}
		
		return tbUserEx;
	}
	
	//入库的操作前根据ID获取的对象信息
	@RequestMapping("/inlibrary-in")
	public String inlibraryIn(Integer id,Model model) {
		
		TbInlibrary tbInlibrary = null;
		
		try {
			tbInlibrary = inLibraryService.getTbInlibraryById(id);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		model.addAttribute("tbInlibrary", tbInlibrary);
		
		return "inlibrary-in";
	}
	
	//入库操作
	@RequestMapping("/inlibraryin")
	@ResponseBody
	public TbUserEx inlibraryIns(TbInlibrary tbInlibrary,Model model) {
		
		TbUserEx tbUserEx = new TbUserEx();
		TbInlibrary dataTbInlibrary = null;
		TbCommodity dataTbCommodity = null;
		
		try{
			dataTbInlibrary = inLibraryService.getTbInlibraryById(tbInlibrary.getId());
			dataTbCommodity = storageService.getTbCommodityById(tbInlibrary.getSid());
			
			//判断两个数据库表中记录必须有效 不能为空
			if(dataTbInlibrary!=null && dataTbCommodity!=null) {
				
				//判断入库的数据库 记录 入库数量 不能小于 你输入的数量 
				if(dataTbInlibrary.getInlibrary()>=tbInlibrary.getInlibrary()) {
					
					//数据库的入库数量 减少
					dataTbInlibrary.setInlibrary(dataTbInlibrary.getInlibrary()-tbInlibrary.getInlibrary());
					//数据库的库存数量增加
					dataTbCommodity.setsStorage(dataTbCommodity.getsStorage()+tbInlibrary.getInlibrary());
					//更新入库数据
					inLibraryService.editInLibrary(dataTbInlibrary);
					//更新库存数据
					storageService.editExisStorage(dataTbCommodity);
					//删除入库表中 数量等于0的删除
					inLibraryService.delnLibraryEqualZero();
				}else {
					tbUserEx.setCode(400);
					tbUserEx.setMsg("入库数量不得大于原有数量");
					return tbUserEx;
				}
				
			}else {
				tbUserEx.setCode(400);
				tbUserEx.setMsg("数据库查询失败");
				return tbUserEx;
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setMsg("数据库查询异常");
			return tbUserEx;
		}
		
		tbUserEx.setCode(200);
		tbUserEx.setMsg("入库成功请刷新");
		
		return tbUserEx;
	}
	
//	@RequestMapping("/getType")
//	@ResponseBody
//	public TbCommodity getType(String name) {
//		
//		TbCommodity tbCommodityByName = null;
//		try {
//			tbCommodityByName = storageService.getTbCommodityByName(name);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//		return tbCommodityByName;
//	}
}
